//
//  GWComentViewController.m
//  百思不得姐
//
//  Created by qianfeng on 16/3/7.
//  Copyright © 2016年 高炜. All rights reserved.
//

#import "GWComentViewController.h"
#import "GWTopicModel.h"
#import "GWTopicCell.h"
#import "GWComment.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import <MJRefresh.h>
#import "GWTopicHeaderView.h"
#import "GWCommentCell.h"
@interface GWComentViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpeace;

@property (nonatomic,strong)NSArray *hotComments;
@property (nonatomic,strong)NSMutableArray *lastCommetns;

@property (nonatomic,strong)NSArray *top_cmt;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@property (nonatomic,assign)NSInteger page;
@property (nonatomic,assign)NSInteger total;
@end

@implementation GWComentViewController
-(AFHTTPSessionManager *)manager
{
    if (_manager==nil) {
        _manager =[AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpBasic];
    
    [self setUpTableHeaderView];
    
    [self setUpRefresh];
}
-(void)setUpRefresh
{
    self.tableView.mj_header =[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewsComment)];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer =[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreComment)];
    self.tableView.mj_footer.hidden =YES;
}
-(void)loadMoreComment
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    NSInteger nextPage =self.page+1;
    GWComment *coment =[self.lastCommetns lastObject];
    NSDictionary *parame =@{
                            @"a":@"dataList",
                            @"c":@"comment",
                            @"data_id":self.topic.ID,
                            @"hot":@"1",
                            @"page":@(nextPage),
                            @"lastcid":coment.ID
                            };
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:parame progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            [self.tableView.mj_footer endRefreshing];
            return ;
        }
        NSArray *newArray  =[GWComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [self.lastCommetns addObjectsFromArray:newArray];
        self.page++;
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}
-(void)loadNewsComment
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSDictionary *parame =@{
                            @"a":@"dataList",
                            @"c":@"comment",
                            @"data_id":self.topic.ID,
                            @"hot":@"1"
                            };
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:parame progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            [self.tableView.mj_header endRefreshing];
            return ;
        }
        
        self.hotComments =[GWComment mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]];
        self.lastCommetns =[GWComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        self.total =[responseObject[@"total"]integerValue];
        
        
        self.page =1;
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}
-(void)setUpTableHeaderView
{
    if (self.topic.top_cmt.count) {
        self.top_cmt =self.topic.top_cmt;
        self.topic.top_cmt =nil;
        [self.topic setValue:@0 forKey:@"cellHeight"];
    }
    UIView *headerView =[[UIView alloc]init];
    GWTopicCell *topicCell =[GWTopicCell topicCell];
    topicCell.topic =self.topic;
    topicCell.size =CGSizeMake(GWScreenW, self.topic.cellHeight);
    [headerView addSubview:topicCell];
    headerView.size =CGSizeMake(GWScreenW, self.topic.cellHeight+GWEssencCellMargin);
    self.tableView.tableHeaderView =headerView;
}
-(void)setUpBasic
{
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([GWCommentCell class]) bundle:nil] forCellReuseIdentifier:@"comment"];
    self.tableView.contentInset =UIEdgeInsetsMake(0, 0, 10, 0);
    self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight =44;
    self.tableView.rowHeight =UITableViewAutomaticDimension;
    self.tableView.backgroundColor =GWGlobalBGColor;
    self.navigationItem.rightBarButtonItem =[UIBarButtonItem itemWithImage:@"comment_nav_item_share_icon" highLightImage:@"comment_nav_item_share_icon_click" target:nil action:nil];
    self.navigationItem.title =@"评论";
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
-(void)keyBoardWillChange:(NSNotification *)note
{
    
    CGRect keyBoardEndFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration =[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGFloat speace =GWScreenH -keyBoardEndFrame.origin.y;
    self.bottomSpeace.constant =speace;
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    if (self.top_cmt.count) {
        self.topic.top_cmt =self.top_cmt;
        [self.topic setValue:@0 forKey:@"cellHeight"];
    }
    [self.manager invalidateSessionCancelingTasks:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger hotCount =self.hotComments.count;
    NSInteger lastCount =self.lastCommetns.count;
    if (hotCount) return 2;
    if (lastCount) return 1;
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger hotCount =self.hotComments.count;
    NSInteger lastCount =self.lastCommetns.count;
    self.tableView.mj_footer.hidden =lastCount<=0||self.total<=lastCount;
    
    if (section==0) {
       return hotCount?hotCount:lastCount;
    }
    return lastCount;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    GWTopicHeaderView *headerView =[GWTopicHeaderView headerViewWithTableView:tableView];
    NSInteger hotCount =self.hotComments.count;
    if (section==0) {
        headerView.title = hotCount?@"热门评论":@"最新评论";
    }
    else
    {
        headerView.title = @"最新评论";
    }
    return headerView;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GWCommentCell *cell =[tableView dequeueReusableCellWithIdentifier:@"comment"];
    
    GWComment *coments =[self comentWithIndexPath:indexPath];
    cell.comment =coments;
    return cell;
}
-(NSArray *)comentsWithSection:(NSInteger)section
{
    NSInteger hotCount =self.hotComments.count;
    if (section==0) {
        return hotCount?self.hotComments:self.lastCommetns;
    }
    return self.lastCommetns;
}
-(GWComment *)comentWithIndexPath:(NSIndexPath *)indexPath
{
    return [self comentsWithSection:indexPath.section][indexPath.row];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    UIMenuController *menuC = [UIMenuController sharedMenuController];
    [menuC setMenuVisible:NO animated:YES];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UIMenuController *menuC = [UIMenuController sharedMenuController];
    if (menuC.isMenuVisible) {
        [menuC setMenuVisible:NO animated:YES];
    }
    else
    {
        GWCommentCell *cell = (GWCommentCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell becomeFirstResponder];
        UIMenuItem *ding =[[UIMenuItem alloc]initWithTitle:@"顶" action:@selector(ding:)];
        UIMenuItem *replay =[[UIMenuItem alloc]initWithTitle:@"回复" action:@selector(replay:)];
        UIMenuItem *report =[[UIMenuItem alloc]initWithTitle:@"举报" action:@selector(report:)];
        menuC.menuItems =@[ding,replay,report];
        CGRect rect =CGRectMake(0, cell.height*0.5, cell.width, cell.height*0.5);
        [menuC setTargetRect:rect inView:cell];
        [menuC setMenuVisible:YES animated:YES];
    }
    
}

-(void)ding:(UIMenuController *)menu
{
    NSIndexPath *indexPath =[self.tableView indexPathForSelectedRow];
    GWComment *cometn =[self comentWithIndexPath:indexPath];
    NSLog(@"%@",cometn.content);
}
-(void)replay:(UIMenuController *)menu
{
    NSIndexPath *indexPath =[self.tableView indexPathForSelectedRow];
    GWComment *cometn =[self comentWithIndexPath:indexPath];
    NSLog(@"%@",cometn.content);
}
-(void)report:(UIMenuController *)menu
{
    NSIndexPath *indexPath =[self.tableView indexPathForSelectedRow];
    GWComment *cometn =[self comentWithIndexPath:indexPath];
    NSLog(@"%@",cometn.content);
}
@end
